package xyz.thoughtset.viewer.executor.core.base;

import lombok.Data;
import lombok.SneakyThrows;
import org.apache.ibatis.parsing.XNode;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Data
public class DataNode {
    private String nodeKey;
    private Integer nodeType = 0;
    private boolean useKey = false;
    private List<String> keyColumnNames = new ArrayList<>();
    private List<DataNode> sonDataNodes = new ArrayList<>();

    DataNode putSonDataNode(DataNode dataNode){
        this.sonDataNodes.add(dataNode);
        return this;
    }

    @SneakyThrows
    public List putValue(ResultSet rs, XNode resultChild, String prefix, Class<?> javaTypeClass
            ,HashMap dataMap,List<String> key){
        String columnPrefix = StringUtils.hasText(prefix) ? prefix : "";
        String property = resultChild.getStringAttribute("property");
        String column = columnPrefix + resultChild.getStringAttribute("column");
        Object value = rs.getObject(column,javaTypeClass);
        dataMap.put(property,value);
        int pos = keyColumnNames.indexOf(column);
        if (pos>=-1){
            key.add(pos,value.toString());
        }
        return key;
    }

    @SneakyThrows
    public DataNode putColumnClew(String columnName){
        if (useKey) return this;
        this.keyColumnNames.add(columnName);
        return this;
    }

    public DataNode putKeyClew(String columnName){
        if (!useKey) this.keyColumnNames = new ArrayList<>();
        useKey = true;
        this.keyColumnNames.add(columnName);
        return this;
    }


    public List<HashMap> combineData(List<HashMap> datas){
//        HashMap<String,Object> combineData = new HashMap<>();
//        for (String columnName : this.idNodeColumnNames) {
//            combineData.put(columnName,this.idNodeMap.get(columnName));
//        }
        return datas;
    }

}
